<script setup lang="ts">
import {
  createConsultOrder,
  getConsultOrderPre as getConsultOrderPreAPI,
  getConsultOrderPayUrl
} from '@/services/consult'
import { getPatientDetail as getPatientDetailAPI } from '@/services/user'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import { onMounted } from 'vue'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { onBeforeRouteLeave } from 'vue-router'

const consultStore = useConsultStore()

// const payInfo = ref<Partial<ConsultOrderPreData>>({})
const payInfo = ref({} as ConsultOrderPreData)

const getConsultOrderPre = async () => {
  const r = await getConsultOrderPreAPI({
    type: consultStore.consult.type, // 首页，选择的类型（一般是急速问诊）
    illnessType: consultStore.consult.illnessType // 急速问诊的类型（普通、三甲）
  })
  payInfo.value = r.data
  // 设置优惠券 ID 到 Pinia
  consultStore.setCoupon(r.data.couponId)
}
// getConsultOrderPre()

const patient = ref({} as Patient)
// 获取患者详情
const getPatientDetail = async () => {
  if (consultStore.consult.patientId) {
    const r = await getPatientDetailAPI(consultStore.consult.patientId)
    patient.value = r.data
  }
}
// getPatientDetail()
/* 110101198307212600
110101196107145504
11010119890512132X
110101196501023433
110101197806108758
110101198702171378
110101198203195893 */

const show = ref(false)
const paymentMethod = ref<0 | 1>()
const agree = ref(false)
const orderId = ref('')
const loading = ref(false)
const submit = async () => {
  if (!agree.value) return showToast('请勾选我已同意支付协议')
  loading.value = true
  // consultStore.consult => 所有前面收集到的信息
  const r = await createConsultOrder(consultStore.consult)
  // 记录订单编号/ID
  orderId.value = r.data.id
  loading.value = false

  // 一旦拿到订单编号了，仓库里面的信息就可以销毁了
  consultStore.clear()
  // 打开
  show.value = true
}

// 离开当前组件的时候会触发的路由钩子
onBeforeRouteLeave(() => {
  if (orderId.value) return false // 阻止离开
})
const router = useRouter()

// 监听关闭弹框之前的事件
const beforeClose = () => {
  // 支持返回 Promise
  return showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付',
    confirmButtonColor: 'var(--cp-primary)'
  })
    .then(() => {
      // 点确定会触发 then，走这儿，return false 就可以阻止关闭
      return false
      // return Promise.resolve(false)
    })
    .catch(() => {
      // 关闭支付，走这儿
      // 清空订单 ID
      orderId.value = ''
      // 跳转到问诊记录页面
      router.push('/user/consult')
      // 表示关闭
      return true
    })
}
// 获取支付地址，跳转到支付地址
const pay = async () => {
  if (!paymentMethod.value) return showToast('请选择支付方式')
  showToast('跳转支付')
  const r = await getConsultOrderPayUrl({
    orderId: orderId.value,
    paymentMethod: paymentMethod.value,
    payCallback: 'http://localhost:5173/room'
  })
  // 注意这里跳转要用 location.href，不能用 router.push（只能是路由配置项里面的那些地址）
  location.href = r.data.payUrl
}

onMounted(() => {
  if (
    !consultStore.consult.type ||
    !consultStore.consult.illnessType ||
    !consultStore.consult.depId ||
    !consultStore.consult.patientId
  ) {
    return showDialog({
      title: '温馨提示',
      message:
        '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付',
      // 回退历史不关闭弹框
      closeOnPopstate: false
    }).then(() => {
      router.push('/')
    })
  }
  // 注释掉了外面的调用，代码走到这儿的时候能保证 store 里面是有信息的
  getConsultOrderPre()
  getPatientDetail()
})
</script>

<template>
  <div class="consult-pay-page" v-if="payInfo.payment && patient.id">
    <cp-nav-bar title="支付" />
    <!-- 提示信息 -->
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <!-- 支付信息 -->
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell
        title="实付款"
        :value="`¥${payInfo.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <!-- 患者信息 -->
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient.name} | ${patient.genderValue} | ${patient.age}岁`"
      ></van-cell>
      <van-cell
        title="病情描述"
        :label="consultStore.consult.illnessDesc"
      ></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>
    <!-- 支付 sheet -->
    <!-- 返回的时候不关闭弹框，close-on-popstate false -->
    <van-action-sheet
      :close-on-popstate="false"
      v-model:show="show"
      title="选择支付方式"
      :closeable="false"
      :before-close="beforeClose"
    >
      <div class="pay-type">
        <p class="amount">￥{{ payInfo.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon>
              <cp-icon name="consult-wechat" />
            </template>
            <template #extra>
              <van-checkbox :checked="paymentMethod === 0" />
            </template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon>
              <cp-icon name="consult-alipay" />
            </template>
            <template #extra>
              <van-checkbox :checked="paymentMethod === 1" />
            </template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay"
            >立即支付</van-button
          >
        </div>
      </div>
    </van-action-sheet>
    <!-- 底部支付按钮 -->
    <van-submit-bar
      :loading="loading"
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="submit"
    />
  </div>
  <div class="consult-pay-page" v-else>
    <van-skeleton :row="3" />
    <van-skeleton :row="5" />
    <van-skeleton :row="4" />
    <van-skeleton :row="6" />
    <van-skeleton :row="2" />
  </div>
</template>

<style lang="scss" scoped>
.van-skeleton {
  margin-bottom: 10px;
}
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}

.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
